import React, { useState } from 'react';
import { connect } from 'umi';
import { Modal, Button, Form, Input, Checkbox, Select, InputNumber, DatePicker,Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import moment from 'moment';

//base64图片文件
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}


class NewProductTypeModal extends React.Component {
  constructor(props) {
    super(props);
    this.form = null;
    this.state = {
      submitBtnLoading: false,
      previewVisible: false,
      previewImage: '',
      fileList: [],
      imgUrl:'',
      machine_name:"", id:"", price:"", machine_function:"", machine_features:"",machine_image:"",create_time:"",
    }
  }
  formRef = React.createRef();

  // handle
  onSubmit = () => {
    this.formRef.current.setFieldsValue({
      machine_name: 'xxx'
    })
    this.formRef.current.validateFields()
      .then(async values => {
        values.machine_image = this.state.imgUrl
        values.id = this.state.imgUrl.split("_")[1].split(".png")[0]
        // console.log("->previewImage",this.state.imgUrl)  http://localhost:8081/pic/type_5.png
        console.log("->vuale",values)
        await this.props.dispatch({type: 'commonModel/saveMachine', payload: values});
        await this.props.hide();
      })
      .catch(errorInfo => {
        console.log(errorInfo)
      });
  };

  handleCancelBtnClick = async () => {
    this.props.hide()
  };

  // life cycle
  initData = async () => {

  };

  componentWillMount() {
    this.initData().then(()=>null)
  }

  //图片预览取消函数
  handleCancel = () => this.setState({ previewVisible: false });

  //图片预览弹窗函数
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  //上传文件改变时的状态，详情可以参考antd的Upload组件API参数
  onChange = ({fileList}) => {
    console.log("->fileList",fileList[0].response)
    if (fileList[0].response!==undefined){
      this.setState({
        imgUrl: fileList[0].response.data,
      });
    }

    this.setState({ fileList });
  };
  componentWillMount() {
    // console.log("->222",this.props.productTypeOne)
    // let { machine_name, id, price, machine_function, machine_features,machine_image,create_time } = this.props.productTypeOne
    // this.setState({
    //   machine_name, id, price, machine_function, machine_features,machine_image,create_time,
    // })
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      productTypeOne: nextProps.productTypeOne,
    })
  }
  componentDidMount() {
    // this.formRef.current.setFieldsValue({machine_name:"dwadada" })
  }

  addonChange = e => {
    this.setState({
      machine_name: e.target.value,
    })
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state;

    return (
      <div>
        <Modal
          title="管理员发布饮用水类型"
          visible={this.props.visible}
          onOk={this.onSubmit}
          onCancel={this.handleCancelBtnClick}
        >
          <Form
            labelCol={{span: 6}}
            wrapperCol={{span: 16}}
            ref={this.formRef}
            name="control-ref"
            onFinish={this.onFinish}
          >

            <Form.Item
                label="饮用水名称"
                name="id"
                style={{display:"none"}}
            >
              <Input placeholder="饮用水名称"/>
            </Form.Item>

            <Form.Item
              label="饮用水名称"
              name="machine_name"
              rules={[{ required: true, message: '请选择饮用水名称' }]}
            >
              <Input placeholder="饮用水名称" type='text' defaultValue={this.props.productTypeOne?.machine_name}  onChange={this.addonChange}/>
            </Form.Item>

            <Form.Item
              label="出售单价"
              name="price"
              rules={[{ required: true, message: '请输入出售单价' }]}
            >
              <InputNumber min={1} max={99999} style={{width: '100%'}} defaultValue={this.props.productTypeOne?.price}/>
            </Form.Item>


            <Form.Item
                label="饮用水标签"
                name="machine_function"
                rules={[{ required: true, message: '请选择饮用水标签' }]}
            >
              <Input type="text" placeholder="饮用水标签" defaultValue={this.props.productTypeOne?.machine_function}/>
            </Form.Item>

            <Form.Item
              label="详细说明"
              name="machine_features"
              rules={[{ required: true, message: '请输入饮用水特色说明' }]}
            >
              <Input.TextArea rows={3} />
            </Form.Item>


            <Form.Item
              label="商品图片"
              name="machine_image"
            >
              <ImgCrop rotate>
                <Upload
                    name="file"
                    action="http://127.0.0.1:8081/uploadFile"
                    accept="image/*"
                    listType="picture"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.onChange}
                >
                  {fileList.length < 1 && '+ 点击上传'}
                </Upload>
              </ImgCrop>

            </Form.Item>

          </Form>
        </Modal>
      </div>
    )

  }


}

function mapStateToProps({ loginModel, commonModel }) {
  const { isLogin, username, user_role } = loginModel;
  const { machineInfo, city_list,saveMachine } = commonModel;
  return { isLogin, username, user_role, machineInfo, city_list,saveMachine };
}

export default connect(mapStateToProps)(NewProductTypeModal);
